package com.xiaorong.controller;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.xiaorong.Principal;
import com.xiaorong.dao.AdminDao;
import com.xiaorong.entity.Admin;
import com.xiaorong.entity.Role;

@Controller
@RequestMapping("/")
public class LoginController extends BaseController{
	
	@Resource
	private AdminDao adminDao;
	
	@RequestMapping(value = "/index.do", method = RequestMethod.GET)
	public String index( Model model, HttpServletRequest request, HttpSession session){
		model.addAttribute("adminUsername",session.getAttribute("adminUsername"));
		return "/index";
	}
	
	@RequestMapping(value = "/logout.do", method = RequestMethod.GET)
	public String logout(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		session.removeAttribute("adminUsername");
		return "redirect:login.html";
	}
	
	@RequestMapping(value = "/submit.do", method = RequestMethod.POST)
	public String submit(String username, String password, HttpSession session){
		if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
			return "redirect:login.html";
		}
		
		Admin admin = adminDao.findByUsername(username);
		if(admin == null){
			return "redirect:login.html";
		}
		if(admin.getPassword().equals(DigestUtils.md5Hex(password))){
			admin.setLastLogin(new Date());
			adminDao.merge(admin);
			session.setAttribute("adminUsername", new Principal(admin.getId(), admin.getName()));
			
			//把权限保存到session中
			Set<String> authorities = new HashSet<String>();
			for(Role role : admin.getRoles()){
				authorities.addAll(role.getAuthorities());
			}
			session.setAttribute("authorities", authorities);
			session.setMaxInactiveInterval(720);
			
			return "redirect:index.do";
			
		}else{
			return "redirect:login.html";
		}
	}
}
